package yang.itcode.controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import yang.itcode.model.Result;
import yang.itcode.service.PurchaseOrderService;

import static yang.itcode.constant.ErrorConstant.*;

@RestController
@RequestMapping("/api/purchase-order")
public class PurchaseOrderController {

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @PostMapping
    public Result<Boolean> createPurchaseOrder(@RequestBody JSONObject obj) {
        if (!purchaseOrderService.createPurchaseOrder(obj)) {
            return Result.error(PURCHASE_ORDER_ADD_EXCEPTION_CODE, PURCHASE_ORDER_ADD_EXCEPTION_MESSAGE);
        }
        return Result.success(true);
    }

    @PostMapping("/list")
    public Result<PageInfo<JSONObject>> getPurchaseOrderList(@RequestBody JSONObject obj) {
        Integer pageNum = obj.getInt("pageNum");
        Integer pageSize = obj.getInt("pageSize");
        JSONObject condition = obj.getJSONObject("condition");
        return Result.success(purchaseOrderService.getPurchaseOrderList(pageNum, pageSize, condition));
    }

    @GetMapping("/{id}")
    public Result<JSONObject> getPurchaseOrder(@PathVariable("id") Integer id) {
        JSONObject detail = purchaseOrderService.getPurchaseOrderDetail(id);
        return Result.success(detail);
    }

    @PutMapping
    public Result<Boolean> updatePurchaseOrder(@RequestBody JSONObject obj) {
        if (purchaseOrderService.updatePurchaseOrder(obj)) {
            return Result.success();
        } else {
            return Result.error(PURCHASE_ORDER_UPDATE_EXCEPTION_CODE, PURCHASE_ORDER_UPDATE_EXCEPTION_MESSAGE);
        }
    }

    @PostMapping("/red/{id}")
    public Result<Boolean> redPurchaseOrder(@PathVariable("id") Integer id) {
        purchaseOrderService.redPurchaseOrder(id);
        return Result.success(true);
    }
}
